﻿using System;
using System.Threading;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Linq;
using System.Security.Principal;
using System.Windows.Forms;

namespace HYQuick
{
    static class Program
    {

        public static NotifyIcon notify = new NotifyIcon();    //指定在通知区域中创建图标的组件
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            if(HYQuickUpdate.LocalUpdate())
            {
                Environment.Exit(0);
                return;
            }

            if(Init())
            {
                Application.Run();
            }
        }

        public static void Quit()
        {
            notify.Visible = false;
            Application.ExitThread();
        }

        static bool Init()
        {
            const string adminComment = "HYQuick当前是以程序员身份运行。此时，您的宿主程序也必须是以管理员身份运行，这样HYQuick快捷菜单才能正常出现。";

            var mutexStr = "_HYQuick__HYQuick__HYQuick__HYQuick__HYQuick_";
            bool canCreateMutex;
            Mutex programMutex = new Mutex(false, mutexStr, out canCreateMutex);  //Mutex->一个同步基元，也可用于进程间同步；互斥锁
            if(canCreateMutex)
            {
                notify = HYQuickNotify.GetNotify();
                notify.Visible = true;

                if(HYQuickConfig.ThisConfig.FirstRun)
                {
                    HYQuickConfig.ThisConfig.FirstRun = false;
                    HYQuickConfig.ThisConfig.TrySave();

                    string additional = IsAdministrator() ? adminComment : string.Empty;

                    notify.ShowBalloonTip("HYQuick已经运行，您可以点击右键查看其选项。" + " " + adminComment);
                }
                else if(IsAdministrator())
                {
                    notify.ShowBalloonTip(adminComment);
                }
                Action silenceUpdate = () =>
                  {
                      HYQuickUpdate.SilenceUpdate();
                  };
                silenceUpdate.BeginInvoke(null, null);   //多线程操作

                HYQuickListener.Listener.Run();
                return true;

            }
            return false;
        }

        public static bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();     //表示Windows用户
            WindowsPrincipal principal = new WindowsPrincipal(identity); //使代码检查Windows用户的Windows组成部分
            return principal.IsInRole(WindowsBuiltInRole.Administrator); //获得当前使用者是不是Windows Adminstrator
        }
    }
}
